/*
 * @name:
 * @test: test font
 * @msg:
 * @param:
 * @return:
 */
const configApp = require("../config/app.js");
import app from "@/config/app";
import {
	toLogin,
	checkLogin
} from "../libs/login";
import store from "../store";

/**
 * 发送请求
 */
function baseRequest(
	url,
	method,
	data, {
		noAuth = false,
		noVerify = false
	},
	params
) {
	let Url = configApp.HTTP_REQUEST_URL,
		header = configApp.HEADER;
	if (params != undefined) {
		header = configApp.HEADERPARAMS;
	}
	if (!noAuth) {
		//登录过期自动登录
		if (!store.state.app.token && !checkLogin()) {
			toLogin();
			return Promise.reject({
				msg: "未登录",
			});
		}
	}
	if (store.state.app.token)
		header[configApp.TOKENNAME] = store.state.app.token;
	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + "/api/front/" + url,
			method: method || "GET",
			header: header,
			data: data || {},
			success: (res) => {
				if (noVerify) reslove(res.data, res);
				else if (res.data.code == 200) reslove(res.data, res);
				else if ([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1) {
					toLogin();
					reject(res.data);
				} else if (res.data.code == 400) {
					uni.showToast({
						title: res.data.message,
						icon: "none",
					});
				} else if (res.data.code == 500) {
					uni.showToast({
						title: res.data.message,
						icon: "none",
					});
				} else {
					console.log(res);
					reject(res.data.message || "系统错误");
				}
			},
			fail: (msg) => {
				console.log(Url + "/api/front/" + url);
				console.log(msg);
				reject("请求失败", msg);
			},
		});
	});
}

const request = {};

["options", "get", "post", "put", "head", "delete", "trace", "connect"].forEach(
	(method) => {
		request[method] = (api, data, opt, params) =>
			baseRequest(api, method, data, opt || {}, params);
	}
);

export default request;